/**
 * 
 */
package com.zho.web.tag;

import java.io.StringReader;

import javax.servlet.jsp.tagext.TagSupport;

import com.zho.common.velocity.SpringVelocityTools;
import com.zho.common.velocity.VelocityHelper;
import com.zho.common.velocity.VelocityTemplate;

import org.apache.log4j.Logger;
import org.apache.velocity.context.Context;


/**
 * @author ho.viet.duan
 *
 */
public abstract class BasicVelocityTag extends TagSupport {
    private static Logger logger = Logger.getLogger(BasicVelocityTag.class);
    protected boolean usingCache = false;

    /**
	 * @return the usingCache
	 */
	public boolean isUsingCache() {
		return usingCache;
	}

	/**
	 * @param usingCache the usingCache to set
	 */
	public void setUsingCache(boolean usingCache) {
		this.usingCache = usingCache;
	}

	/**
     * get real template path of static page
     */
    protected abstract String getTemplatePath();
    
    /**
     * 
     * @param context
     */
    protected abstract void populateContextParam(Context context) throws Exception ;
    
    /**
     * 
     * @return
     */
    public String generate() {
        return generate(null);
    }
    
    /**
     * 
     * @return static page file
     */
    public String generate(Context ctx) {
        try {
            //+++ step 1:get template path
            String tmpFilePath = this.getTemplatePath();
            if(tmpFilePath != null && tmpFilePath.length() > 0) {
                //+++ step 2:
                StringReader source = VelocityTemplate.getTemplateContent(tmpFilePath, usingCache);
                
                ctx = (ctx == null ? SpringVelocityTools.createContext() : ctx);
                //+++ step 3: populate context Params                            
                this.populateContextParam(ctx);
                
                //+++ step 4: generate output
                return VelocityHelper.execute(source, ctx);
            }
        } catch (Exception e) {
            logger.warn("generate()", e);
        }
        return "";
    }
}
